package com.projecetest.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.projecetest.eduservice.entity.EduSubject;
import com.projecetest.eduservice.entity.excel.SubjectData;
import com.projecetest.eduservice.entity.subject.OneSubject;
import com.projecetest.eduservice.entity.subject.TwoSubject;
import com.projecetest.eduservice.listener.SubjectExcelListener;
import com.projecetest.eduservice.mapper.EduSubjectMapper;
import com.projecetest.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Captain
 * @since 2021-07-31
 */

@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        try {
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch (Exception e){

        }
    }

    //返回树形数据列表
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询数据
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);

        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperOne.ne("parent_id","0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo);

        //封装数据
        List<OneSubject> parentSubjectList = new ArrayList<>();

        for (EduSubject eduSubject : oneSubjectList) {
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject);
            parentSubjectList.add(oneSubject);

            List<TwoSubject> childrenSubjectList = new ArrayList<>();

            for (EduSubject twoEduSubject : twoSubjectList) {
                if (twoEduSubject.getParentId().equals(eduSubject.getId()))
                {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(twoEduSubject,twoSubject);
                    childrenSubjectList.add(twoSubject);
                }
            }
            oneSubject.setChildren(childrenSubjectList);
        }


        return parentSubjectList;
    }
}
